package com.itheima;

import com.itheima.utils.DownLoadUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/downloadServlet")
public class downloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //获取从下载页面出传送过来的下载文件名
        String filename = request.getParameter("filename");

        //获取客户端的浏览器版本
        String agent = request.getHeader("user-agent");

        //使用工具类,将我们获取到的浏览器版本和下载文件的名称相结合
       filename= DownLoadUtils.getFileName(agent,filename);

        //找到相对于的文件名,建立一个输入流
        InputStream in = getServletContext().getResourceAsStream("/img/" + filename);

        //建立输出流,但是如果只建立一个输出流的话,就只是单纯的展示图片而已,并不是下载
        //所以我们需要在相应上对响应头进行一个声明,我们现在是进行一个附件下载的操作
        response.setHeader("content-disposition","attachment;filename"+filename);
        //然后建立一个字节输出流
        ServletOutputStream out = response.getOutputStream();
        IOUtils.copy(in,out );
    }
}
